package cn.shuangze.assetsms.dao.impl;

import cn.shuangze.assetsms.dao.AssetsTrjnDao;
import cn.shuangze.assetsms.dao.DBUtil;
import cn.shuangze.assetsms.entity.AssetsTrjn;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import static cn.shuangze.assetsms.dao.DBUtil.exceuteUpdate;
import static cn.shuangze.assetsms.dao.DBUtil.getConnection;

public class AssetsTrjnDaoJDBCImpl implements AssetsTrjnDao {
    @Override
    public int add(AssetsTrjn assetsTrjn) throws Exception {
        String sql = "insert into AssetsTrjn(FromAcc,AssetsID,RegDate,PersonID,purpose,Other) values(?,?,?,?,?,?)";
        try (Connection conn = getConnection();) {
            return exceuteUpdate(conn, sql, new Object[]{
                    assetsTrjn.getFromAcc(),
                    assetsTrjn.getAssetsId(),
                    assetsTrjn.getRegDate(),
                    assetsTrjn.getPersonID(),
                    assetsTrjn.getPurpose(),
                    assetsTrjn.getOther()
            });
        }
    }

    @Override
    public String[][] findType(String type) throws Exception {
        String sql = "select * from AssetsTrjn where FromAcc=?";
        List<AssetsTrjn> list = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pst = conn.prepareStatement(sql)) {

            pst.setString(1, type);

            try (ResultSet rs = pst.executeQuery()) {
                while (rs.next()) {
                    list.add(new AssetsTrjn(
                            rs.getInt("JourNo"),
                            rs.getString("FromAcc"),
                            rs.getInt("AssetsID"),
                            rs.getDate("RegDate"),
                            rs.getInt("PersonID"),
                            rs.getString("purpose"),
                            rs.getString("Other")
                    ));
                }
            }

        }
        String[][] sn = null;
        int size = list.size();
        if (!list.isEmpty()) {
            sn = new String[list.size()][7];
        }
        for (int i = 0; i < size; i++) {
            sn[i][0] = String.valueOf(list.get(i).getJourNo());
            sn[i][1] = list.get(i).getFromAcc();
            sn[i][2] = String.valueOf(list.get(i).getAssetsId());
            sn[i][3] = String.valueOf(list.get(i).getRegDate());
            sn[i][4] = String.valueOf(list.get(i).getPersonID());
            sn[i][5] = String.valueOf(list.get(i).getPurpose());
            sn[i][6] = list.get(i).getOther();
        }
        return sn;
    }

}
